package com.atguigu.gmall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.RedisConstant;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.user.dto.UserLoginDto;
import com.atguigu.gmall.user.vo.UserLoginSuccessVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.user.entity.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @author Administrator
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2023-11-17 09:54:58
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String , String> redisTemplate ;

    @Override
    public UserLoginSuccessVo login(UserLoginDto userLoginDto) {

        // 数据校验
        String loginName = userLoginDto.getLoginName();
        String passwd = userLoginDto.getPasswd();
        if(StringUtils.isEmpty(loginName) || StringUtils.isEmpty(passwd)) {
            throw new GmallException(ResultCodeEnum.LOGIN_ERROR) ;
        }

        // 根据用户名查询用户数据
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>() ;
        lambdaQueryWrapper.eq(UserInfo::getLoginName , loginName) ;
        UserInfo userInfo = this.getOne(lambdaQueryWrapper);
        if(userInfo == null) {
            throw new GmallException(ResultCodeEnum.LOGIN_ERROR) ;
        }

        // 判断密码
        String digestPasswd = DigestUtils.md5DigestAsHex(passwd.getBytes());
        if(!digestPasswd.equals(userInfo.getPasswd())) {
            throw new GmallException(ResultCodeEnum.LOGIN_ERROR) ;
        }

        // 保存登录状态
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(RedisConstant.REDIS_USER_LOGIN + token , JSON.toJSONString(userInfo) , 7 , TimeUnit.DAYS);

        // 构建响应结果数据
        UserLoginSuccessVo userLoginSuccessVo = new UserLoginSuccessVo() ;
        userLoginSuccessVo.setToken(token);
        userLoginSuccessVo.setNickName(userInfo.getNickName());

        // 远程调用service-cart微服务的接口完成购物车数据的合并 , 透传用户的id和临时用户id

        // 返回
        return userLoginSuccessVo;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(RedisConstant.REDIS_USER_LOGIN + token ) ;
    }

}




